﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ECommerce.Model.Order;
using ECommerce.BLL.Order;
using Jzy.Core.Common.Web;
using Jzy.Core.Common;
using Jzy.Common;
using Jzy.Core.Common.Basic;
using Jzy.Core.Utility;
using Syncfusion.XlsIO;
using Com.Alipay;
using System.Xml;
using System.Text;
using Jzy.Core.Log.Exceptions;
using ECommerce.BLL.Member;
using ECommerce.Model.Member;
using ECommerce.Common;

namespace ECommerce.Web.ECAdmin.Order
{
    public partial class List : PageList
    {
        private OrderState State
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString["State"]))
                {
                    return (OrderState)int.Parse(Request.QueryString["State"]);
                }
                else
                {
                    return OrderState.未处理;
                }
            }
        }
        private string PayStates
        {
            get
            {
                return Request.QueryString["PayState"];
            }
        }

        private ECOrderBO Order
        {
            get
            {
                return ECOrderBO.Instance<ECOrderBO>();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindPayState();

                if (!string.IsNullOrEmpty(Request["Name"]))
                {
                    txtName.Text = Request.QueryString["Name"];
                }
                
                
                BindView();

                if (!string.IsNullOrEmpty(PayStates))
                {
                    drpPayState.SelectedValue = PayStates;
                }
            }
            
            base.InitSelectID(hidSelectIDs);
            AddAttr();
        }

        private void BindPayState()
        {
            List<EnumInfo> list = ConvertUtil.ConvertEnum(typeof(PayState));
            list.Insert(0, new EnumInfo() { ID = -1, Name = "全部" });
            drpPayState.DataTextField = "Name";
            drpPayState.DataValueField = "ID";
            drpPayState.DataSource = list;
            drpPayState.DataBind();
        }

        private void AddAttr()
        {
            litTitle.Text = State.ToString() + "订单";
            JSUtil.ClickBtn(lnkTransfer, btnTransfer);
            JSUtil.ClickBtn(lnkSend, btnSend);
            JSUtil.ClickBtn(lnkComplete, btnComplete);
            JSUtil.ClickBtn(lnkFail, btnFail);
            
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindView();
        }

        private void BindView()
        {
            LVUtil.Init(lv, lvHeader);
            lv.EnableViewState = true;

            PagerSetting setting = new PagerSetting();
            setting.PageIndex = this.PageIndex;
            setting.PageSize = AppConfig.PageSize;
            setting.OrderBy = "InputTime desc";
            setting.Where = "OrderState = " + (int)State;

            if (drpPayState.SelectedValue != "-1")
            {
                setting.Where += " and PayState=" + drpPayState.SelectedValue;
            }

            if (txtName.Text.Trim() != "")
            {
                setting.Where += " and (ID like @p0 or MemberLoginName like @p0)";
            }

            string prefix = GlobalVar.WebCurrPath + "List.aspx?Name=" + Server.UrlEncode(txtName.Text) + "&State=" + (int)State + "&PayState=" + drpPayState.SelectedValue;

            IEnumerable<ECOrderInfo> list = this.Order.GetList(setting, "%" + txtName.Text + "%");
            lv.DataKeyNames = new string[] { "ID" };
            lv.DataSource = list;
            lv.DataBind();

            litPager.Text = HtmlPager.Render(setting, prefix, true);

            
        }

        protected void btnTransfer_Click(object sender, EventArgs e)
        {
            if (strSelectIDs != "")
            {
                Order.SetOrderState(StrUtil.SplitToStr(strSelectIDs), OrderState.已处理);
            }
            BindView();
        }

        protected void btnExportSelect_Click(object sender, EventArgs e)
        {
            BindView();
        }

        protected void btnExportAll_Click(object sender, EventArgs e)
        {
            BindView();
        }


        private void ExportExcell(List<ECOrderInfo> list)
        {
            

            ExcelEngine engine = new ExcelEngine();
            IApplication app = engine.Excel;
            IWorkbook book = app.Workbooks.Add();
            IWorksheet sheet = book.Worksheets[0];
            sheet.PageSetup.CenterHorizontally = true;
            sheet.PageSetup.Orientation = ExcelPageOrientation.Landscape;
            sheet.PageSetup.TopMargin = 0.5;
            sheet.PageSetup.LeftMargin = 0.5;
            sheet.PageSetup.RightMargin = 0.5;



            sheet.Range[1, 1].Text = "缺陷标题";
            sheet.Range[1, 1].RowHeight = 15;
            sheet.Range[1, 1].ColumnWidth = 15;

            sheet.Range[1, 2].Text = "优先级";

            sheet.Range[1, 3].Text = "缺陷描述";
            sheet.Range[1, 3].ColumnWidth = 100;

            sheet.Range[1, 4].Text = "缺陷类型";

            sheet.Range[1, 5].Text = "期望完成日期";
            sheet.Range[1, 5].ColumnWidth = 15;

            sheet.Range[1, 1, 1, 5].CellStyle.Font.Bold = true;


            //HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
            //HttpContext.Current.Response.Charset = "UTF-8";
            //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
            //HttpContext.Current.Response.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
            //ctl.Page.EnableViewState = false;
            //System.IO.StringWriter tw = new System.IO.StringWriter();
            //System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            //ctl.RenderControl(hw);
            //HttpContext.Current.Response.Write(tw.ToString());
            //HttpContext.Current.Response.End(); 

            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    DataRow dr = dt.Rows[i];
            //    sheet.Range[i + 2, 1].Text = dr["Name"].ToString();

            //    sheet.Range[i + 2, 2].Text = ((BugPriority)(int)dr["Priority"]).ToString();
            //    sheet.Range[i + 2, 3].Text = dr["Remark"].ToString();
            //    sheet.Range[i + 2, 3].WrapText = true;
            //    sheet.Range[i + 2, 4].Text = dr["TypeName"].ToString();

            //    if (dr["PlanEndTime"] != DBNull.Value)
            //    {
            //        sheet.Range[i + 2, 5].Text = ((DateTime)dr["PlanEndTime"]).ToString("yyyy-MM-dd");
            //    }

            //    sheet.Range[i + 2, 1, i + 2, 5].VerticalAlignment = ExcelVAlign.VAlignCenter;
            //}

            //for (int i = 1; i < dt.Rows.Count + 2; i++)
            //{
            //    for (int j = 1; j < 6; j++)
            //    {
            //        IRange range = sheet.Range[i, j];
            //        IBorders border = range.CellStyle.Borders;

            //        border.LineStyle = ExcelLineStyle.Thin;

            //        border[ExcelBordersIndex.DiagonalDown].LineStyle = border[ExcelBordersIndex.DiagonalUp].LineStyle = ExcelLineStyle.None;
            //    }
            //}

            //book.SaveAs("bug.xls", ExcelSaveType.SaveAsXLS, Response, ExcelDownloadType.PromptDialog);
        }

       

        protected void lv_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                ECOrderInfo info = ((ListViewDataItem)e.Item).DataItem as ECOrderInfo;
                LinkButton btnSendConfirm = e.Item.FindControl("btnSendConfirm") as LinkButton;

                if (info.PayState != (int)PayState.等待发货)
                {
                    btnSendConfirm.Visible = false;
                }
            }
        }

        protected void lv_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            long orderID = long.Parse(e.CommandArgument.ToString());

            ECOrderPayBO orderPay = new ECOrderPayBO();
            ECOrderPayInfo payInfo = orderPay.GetInfoByOrderID(orderID);
            ////////////////////////////////////////////请求参数////////////////////////////////////////////

            //必填参数//

            //支付宝交易号，支付宝根据商户请求，创建订单生成的支付宝交易号。
            string trade_no = payInfo.Remark;


            //物流公司名称，物流公司名称
            string logistics_name = "999蛋糕网";


            //物流发货单号
            string invoice_no = orderID.ToString();


            //物流发货时的运输类型，三个值可选：POST（平邮）、EXPRESS（快递）、EMS（EMS）
            string transport_type = "EXPRESS";
            //建议与创建交易时选择的运输类型一致

            ////////////////////////////////////////////////////////////////////////////////////////////////

            //把请求参数打包成数组
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("trade_no", trade_no);
            sParaTemp.Add("logistics_name", logistics_name);
            sParaTemp.Add("invoice_no", invoice_no);
            sParaTemp.Add("transport_type", transport_type);

            //请在这里加上商户的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表

            //构造确认发货接口，无需修改

            Service ali = new Service();
            XmlDocument xmlDoc = ali.Send_goods_confirm_by_platform(sParaTemp);
            StringBuilder sbxml = new StringBuilder();
            string nodeIs_success = xmlDoc.SelectSingleNode("/alipay/is_success").InnerText;
            if (nodeIs_success != "T")//请求不成功的错误信息
            {
                string errorMsg = xmlDoc.SelectSingleNode("/alipay/error").InnerText;
                JSUtil.Alert("发货失败：" + errorMsg);

                ExceptionLogBO.Save(new Exception(errorMsg));
            }
            else//请求成功的支付返回宝处理结果信息
            {
                JSUtil.Alert("发货成功");
            }

          //  Response.Write(sbxml.ToString());

            BindView();
        }

        protected void drpPayState_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindView();
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            if (strSelectIDs != "")
            {
                Order.SetOrderState(StrUtil.SplitToStr(strSelectIDs), OrderState.配送中);
            }
            BindView();
        }

        protected void btnComplete_Click(object sender, EventArgs e)
        {
            if (strSelectIDs != "")
            {
               // Order.SetOrderState(StrUtil.SplitToStr(strSelectIDs), OrderState.已结束);
                MemberBaseBO member = new MemberBaseBO();
                List<long> ids = strSelectIDs.Trim(',').Split(',').Select(T=>long.Parse(T)).ToList();
                foreach (long id in ids)
                {
                    ECOrderInfo info = this.Order.GetInfo(id);
                    if (info.OrderState != (int)OrderState.已结束)
                    {
                        info.PayState = (int)PayState.已支付;
                        info.OrderState = (int)OrderState.已结束;

                        MemberBaseInfo memberInfo = member.GetInfo(info.MemberID);
                        memberInfo.Integral += (int)info.TradeValue ;

                        member.Save(memberInfo);
                        this.Order.Save(info);
                    }
                }
            }
            BindView();
        }

        protected void btnFail_Click(object sender, EventArgs e)
        {
            if (strSelectIDs != "")
            {
                Order.SetOrderState(StrUtil.SplitToStr(strSelectIDs), OrderState.未完成);
            }
            BindView();
        }
    }
}